package com.suyu.service.impl;

import com.suyu.common.BaseResponse;
import com.suyu.common.ResultUtils;
import com.suyu.constant.FileConstant;
import com.suyu.model.dto.file.FileInfoDto;
import com.suyu.service.FileService;
import com.suyu.service.FileStorageService;
import io.minio.messages.Item;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author tmh
 * @date 2023/9/24 21:19
 * @description
 */
@Service
public class FileServiceImpl implements FileService {

    @Resource
    private FileStorageService fileStorageService;

    /**
     * 获取所有文件的信息
     * @return
     */
    @Override
    public BaseResponse<List<FileInfoDto>> getFileInfo() {
        List<FileInfoDto> list = new ArrayList<>();
        List<Item> allFiles = fileStorageService.getAllFiles();
        for (Item allFile : allFiles) {
            FileInfoDto fileInfoDto = new FileInfoDto();
            String filePathAndName = allFile.objectName();
            //判断filePathAndName是否包含"/"
            if (filePathAndName.contains("/")) {
                String[] split = filePathAndName.split("/");
                fileInfoDto.setFileName(split[split.length - 1]);
            }else {
                fileInfoDto.setFileName(filePathAndName);
            }
            int index = filePathAndName.indexOf(".");
            if (index == -1) {
                fileInfoDto.setFileType(FileConstant.UNKNOWN_TYPE);
            } else {
                String type = filePathAndName.substring(index + 1);
                if ("jpg".equals(type)||"png".equals(type)) {
                    fileInfoDto.setFileType(FileConstant.IMAGE_TYPE);
                }
                if ("m3u8".equals(type)) {
                    fileInfoDto.setFileType(FileConstant.VIDEO_TYPE);
                }
                if ("txt".equals(type)) {
                    fileInfoDto.setFileType(FileConstant.TEXT_TYPE);
                }
            }
            fileInfoDto.setFileSize(allFile.size() + FileConstant.FILE_SIZE_UNIT);
            fileInfoDto.setDownLoadFileUrl(FileConstant.BASE_URL + "/" + filePathAndName);
            list.add(fileInfoDto);
        }
        return ResultUtils.success(list);
    }
}
